<template>
    <div>
        <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽">
        </el-switch>
        <el-button  v-if="draggable" @click="updateSort" type="primary">批量更新</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-tree :data="data" :props="defaultProps" 
            :expand-on-click-node="false"
            show-checkbox
            node-key="catId" :default-expanded-keys=expendKeys
            :draggable="draggable" :allow-drop="allowDrop" ref="tree"
            @node-drop="handleDrop">
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                <el-button
                    type="text"
                    size="mini"
                    @click="() => append(data)">
                    添加
                </el-button>
                <el-button
                    type="text"
                    size="mini"
                    @click="() => edit(data)">
                    更新
                </el-button>
                <el-button
                    type="text"
                    size="mini"
                    @click="() => remove(node, data)">
                    删除
                </el-button>
                </span>
            </span>
        </el-tree>

        <el-dialog
            title="新增类别"
            :visible.sync="dialogVisible"
            width="30%">

            <el-form :model="categoryForm">
                <el-form-item label="类别名称" :label-width="formLabelWidth">
                    <el-input v-model="categoryForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="图标" :label-width="formLabelWidth">
                    <el-input v-model="categoryForm.icon" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="计量单位" :label-width="formLabelWidth">
                    <el-input v-model="categoryForm.productUnit" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
            </el-dialog>
    </div>
</template>

<script>
/* eslint-disable */ 
export default {
    data() {
      return {
        draggable: false,
        updateNodes:[],
        categoryForm:{
            name:null,
            icon:null,
            productUnit:null,
            catLevel:null,
            parentCid:null,
            showStatus:1,
            sort:0
        },
        data: [],
        expendKeys:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        dialogVisible: false,
        formLabelWidth: '120px',
        dialogType: true,
        maxLevel: 0,
        pCids: []
      };
    },
    methods: {
      getCategory(){
       this.$http({
        url: this.$http.adornUrl('/product/category/listTree'),
        method: 'get'
       }).then(({data})=>{
        // console.log("成功获取的类别数据",data.data)
        this.data = data.data
       })     
      },
      handleNodeClick(data) {
        console.log(data);
      },
      append(data) {
        this.dialogType = true;
        this.categoryForm.name = null;
        this.categoryForm.icon = null;
        this.categoryForm.productUnit = null;
        this.categoryForm.parentCid = data.catId;
        this.categoryForm.catLevel = data.catLevel+1;
        this.categoryForm.showStatus = 1;
        this.categoryForm.sort = 0;
        this.dialogVisible = true;
      },
      edit(data){
        this.dialogType = false;
        this.$http({
            url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
            method: "post",
            data: this.$http.adornData(this.categoryForm, false),
        }).then(({data})=>{
            // console.log("获取数据",data);
            //fill old data
            this.categoryForm.name = data.category.name;
            this.categoryForm.productUnit = data.category.productUnit;
            this.categoryForm.icon = data.category.icon;
            this.categoryForm.catLevel = data.category.catLevel;
            this.categoryForm.parentCid = data.category.parentCid;
            //update data
            this.categoryForm.catId = data.category.catId;
            this.categoryForm.showStatus = 1;
            this.categoryForm.sort = 0;

            //update category
            this.dialogVisible = true;
        });

      },
      submitForm(){
        if(this.dialogType){
            this.addDialog();
        }else{
            this.editDialog();
        }
      },
      addDialog(){
        this.$http({
            url: this.$http.adornUrl("/product/category/save"),
            method: "post",
            data: this.$http.adornData(this.categoryForm, false),
        }).then(({data})=>{
            if (data && data.code === 0) {
              this.$message({
                message: "数据添加成功",
                type: "success",
              });
              this.dialogVisible = false; // 关闭弹出窗口
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expendKeys = [this.categoryForm.parentCid];
            } else {
              this.$message.error(data.msg);
            }
        });
      },
      editDialog(){
        this.$http({
            url: this.$http.adornUrl("/product/category/update"),
            method: "post",
            data: this.$http.adornData(this.categoryForm, false),
        }).then(({data})=>{
            if (data && data.code === 0) {
              this.$message({
                message: "数据更新成功",
                type: "success",
              });
              this.dialogVisible = false; // 关闭弹出窗口
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expendKeys = [this.categoryForm.parentCid];
            } else {
              this.$message.error(data.msg);
            }
        });
      },
      batchDelete(){
        let catIds = [];
        let checkedNodes = this.$refs.tree.getCheckedNodes(false,false);
        // console.log("---->",checkedNodes);
        for(let i=0;i<checkedNodes.length;i++){
            catIds.push(checkedNodes[i].catId);
        }
        this.$confirm(`是否确认删除【${catIds}】记录?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(()=>{
            this.$http({
                url: this.$http.adornUrl('/product/category/delete'),
                method: 'post',
                data: this.$http.adornData(catIds, false),
            }).then(({data})=>{
                if (data && data.code === 0) {
                    this.$message({
                        message: "操作成功",
                        type: "success",
                    });
                    // 重新加载所有的菜单数据
                    this.getCategory();
                    // 设置默认展开的父节点信息
                    this.expendKeys=this.pCids;
                } else {
                    this.$message.error(data.msg);
                }
            })  
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }); 
      },
      remove(node, data) {
        const ids = [data.catId]
        this.$confirm(`是否确认删除【${data.name}】记录?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(()=>{
            this.$http({
                url: this.$http.adornUrl('/product/category/delete'),
                method: 'post',
                data: this.$http.adornData(ids, false),
            }).then(({data})=>{
                if (data && data.code === 0) {
                    this.$message({
                        message: "操作成功",
                        type: "success",
                    });
                    // 重新加载所有的菜单数据
                    this.getCategory();
                    // 设置默认展开的父节点信息
                    this.expendKeys=[node.parent.data.catId]
                } else {
                    this.$message.error(data.msg);
                }
            })  
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });     
      },
      handleDrop(draggingNode, dropNode, dropType, ev){
        //1.拖拽阶段父节点修改
        let parentId = 0;
        let siblings = null;
        if(dropType == 'inner'){
            parentId = dropNode.data.catId;
            siblings = dropNode.childNodes;
        }else{
            parentId = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
            siblings = dropNode.parent.childNodes;
        }
        //2.排序
        for(let i=0;i<siblings.length;i++){
            if(siblings[i].data.catId == draggingNode.data.catId){
                //3.catLevel更新
                let catLevel = draggingNode.level;
                if(siblings[i].level != draggingNode.level){
                    catLevel = siblings[i].level;
                    this.updateChildNodeLevel(siblings[i]);
                }
                this.updateNodes.push({catId:siblings[i].data.catId,sort:i,parentCid:parentId,catLevel:catLevel});
            }else{
                this.updateNodes.push({catId:siblings[i].data.catId,sort:i});
            }
        }
        // console.log("---->",this.updateNodes);
        // this.updateSort(parentId);
        this.pCids.push(parentId)
      },
      updateSort(){
        this.$http({
            url: this.$http.adornUrl("/product/category/updateBatch"),
            method: "post",
            data: this.$http.adornData(this.updateNodes, false),
        }).then(({data})=>{
            if (data && data.code === 0) {
              this.$message({
                message: "数据批量更新成功",
                type: "success",
              });
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expendKeys = this.pCids;
              this.pCids = [];
              this.updateNodes = [];
              this.maxLevel = 0;
            } else {
              this.$message.error(data.msg);
            }
        });
      },
      updateChildNodeLevel(node){
        if(node.childNodes != null && node.childNodes.length > 0){
            for(let i=0;i<node.childNodes.length;i++){
                var childNode = node.childNodes[i].data;
                this.updateNodes.push({catId:childNode.catId,catLevel:node.childNodes[i].level});
                this.updateChildNodeLevel(node.childNodes[i]);
            }
        }
      },
      allowDrop(draggingNode,dropNode,type){
        this.countNodeLevel(draggingNode);
        let deep = Math.abs(this.maxLevel - draggingNode.level)+1;
        if(type == 'inner'){
            return deep + dropNode.level <= 3;
        }
        return deep + dropNode.parent.level <= 3;
      },
      countNodeLevel(node){
        this.maxLevel = node.level;
        if(node.childNodes !=null && node.childNodes.length > 0){
            for(let i=0;i<node.childNodes.length;i++){
                if(node.childNodes[i].level > this.maxLevel){
                    this.maxLevel = node.childNodes[i].level;
                }
                this.countNodeLevel(node.childNodes[i]);
            }
        }
      }
    },
    created(){
        this.getCategory();
    }
  };
</script>

<style>

</style>
